package com.wawayaya.manager;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;

import com.wawayaya.AppContext;
import com.wawayaya.base.BaseFragment;
import com.wawayaya.db.bookshelf.RequestThread;
import com.wawayaya.fragment.ExploreFragment;
import com.wawayaya.fragment.FragmentFactory;
import com.wawayaya.fragment.HomeFragment;
import com.wawayaya.fragment.MyLibraryFragment;
import com.wawayaya.util.PreferenceUtils;
import java.util.Observable;
import wawayaya.kids_iread.R;

/**
 * 管理Fragment切換，观察者模式--观察者
 * Created by David on 2015/11/7.
 * @author Daivd
 */
public class UiFragmentManager extends Observable {
    private static String TAG = "UiFragmentManager";
    private static UiFragmentManager instance;

    AppContext  appContext ;

    private UiFragmentManager() {
        appContext = AppContext.getInstance();
    }

    public static UiFragmentManager getInstance() {
        if(null==instance){
            instance = new UiFragmentManager();
        }
        return instance;
    }

    //记录前一个Fragment
    private BaseFragment previousFragment = null;
    //记录当前Fragmengt
    private BaseFragment currentFragment = null;
    //目标Fragmengt
    private BaseFragment targetFragment = null;

    private FragmentManager mFragmentManager;

    private Boolean isAdd = false;

    /**
     * @return 当前显示Fragment
     */
    public BaseFragment getCurrentFragment() {
        return currentFragment;
    }

    /**
     * @return 前一个显示Fragment
     */
    public BaseFragment getPreviousFragment() {
        return previousFragment;
    }

    /**
     * @return 即将显示Fragment
     */
    public BaseFragment getTargetFragment() {
        return targetFragment;
    }

    /**
     * @return 当前FragmentManager
     */
    public android.support.v4.app.FragmentManager getFragmentManager() {

        return mFragmentManager == null ? null : mFragmentManager;
    }

    /**
     * 切换 fragment
     * @param targetClazz
     * @param fragmentManager
     * @param
     */
    public void changeFragment(Class<? extends BaseFragment> targetClazz,FragmentManager fragmentManager, RequestThread requestThread) {

        this.mFragmentManager = fragmentManager;

        // 第一次切换
        // 对比：目标（targetClazz） VS 当前正在显示(currentFragment)
        if (PreferenceUtils.getBoolean(appContext, "firstOpen", true)) {
            previousFragment = null;
            currentFragment = null;
            targetFragment = null;
            isAdd = false;
        }

        //目标Fragment唯一标识
        String target = targetClazz.getSimpleName();

        if (fragmentManager.findFragmentByTag(target) != null) {
            targetFragment = (BaseFragment) fragmentManager.findFragmentByTag(target);
            isAdd = true;
        } else {
            targetFragment = FragmentFactory.CACHE_MAP.get(target);
            isAdd = false;
        }

        if (targetFragment == null) {
            if ("HomeFragment".equals(target)) {
                targetFragment = new HomeFragment(requestThread);
            }
            if ("ExploreFragment".equals(target)) {
                targetFragment = new ExploreFragment();
            }
            if ("MyLibraryFragment".equals(target)) {
                targetFragment = new MyLibraryFragment();
            }
            isAdd = false;
            FragmentFactory.CACHE_MAP.put(target, targetFragment);
        }

        if(currentFragment!=null && currentFragment==targetFragment){
            return ;
        }
        if ((targetFragment instanceof ExploreFragment || targetFragment instanceof MyLibraryFragment)
                && (currentFragment instanceof HomeFragment  || currentFragment == null)) {

            if (currentFragment != null) {
                fragmentManager.beginTransaction()
                        .detach(currentFragment)
                        .add(R.id.ll_contentview, targetFragment, null)
                        .commitAllowingStateLoss();
            } else {
                fragmentManager.beginTransaction()
                        .replace(R.id.ll_contentview, targetFragment, null)
                        .commitAllowingStateLoss();
            }
        }else{
            if(!isAdd){
                fragmentManager.beginTransaction()
                        .add(R.id.ll_contentview, targetFragment, target)
                        .commitAllowingStateLoss();
            }

            if (currentFragment != null && (currentFragment instanceof ExploreFragment || currentFragment instanceof MyLibraryFragment)) {
                fragmentManager.beginTransaction()
                        .remove(currentFragment)
                        .attach(targetFragment)
                        .commitAllowingStateLoss();
            } else if (currentFragment != null && !(currentFragment instanceof ExploreFragment || currentFragment instanceof MyLibraryFragment)) {
                fragmentManager.beginTransaction()
                        .detach(currentFragment)
                        .attach(targetFragment)
                        .commitAllowingStateLoss();
            }
        }
        previousFragment = currentFragment;
        currentFragment = targetFragment;
        //切换
        changeBottomBar();
    }

    private void changeBottomBar() {
        setChanged();
        notifyObservers(currentFragment.getId());
    }

    /**
     * 避免出现bug，currentFragment置空
     */
    public void setCurrentFragmentEmpty() {

        if (currentFragment != null) {
            currentFragment = null;
        }
    }
}

